<?php
namespace common\services\pay\iosPay;
use linslin\yii2\curl\Curl;
use yii\base\Exception;

/**
 * 21000 App Store无法读取你提供的JSON数据
 * 21002 收据数据不符合格式
 * 21003 收据无法被验证
 * 21004 你提供的共享密钥和账户的共享密钥不一致
 * 21005 收据服务器当前不可用
 * 21006 收据是有效的，但订阅服务已经过期。当收到这个信息时，解码后的收据信息也包含在返回内容中
 * 21007 收据信息是测试用（sandbox），但却被发送到产品环境中验证
 * 21008 收据信息是产品环境中使用，但却被发送到测试环境中验证
 */
class IosPay {

    public $buyUrl = 'https://buy.itunes.apple.com/verifyReceipt'; //正式环境 验证请求
//    public $buyUrl = 'https://sandbox.itunes.apple.com/verifyReceipt'; //测试环境URL

    public function __construct()
    {
        $this->buyUrl = 'https://buy.itunes.apple.com/verifyReceipt'; //正式环境 验证请求
    }


    public function verifyPay($receiptData = '', $url = "") {
        $apiUrl = $url ? $url : $this->buyUrl;
        $params = '{"receipt-data" : "'.$receiptData.'"}';

        $curl = new Curl();
        $curl->setRawPostData($params);
        $res = $curl->post($apiUrl);
        $res = json_decode($res, true);
        $status = $res['status'];

        if ($status == 21007) {
            # 切换URL地址，不需要重复切换地址
            $result = $this->verifyPay($receiptData,'https://sandbox.itunes.apple.com/verifyReceipt');
            return $result;
        }

        $payTime = $res['receipt']['in_app'][0]['purchase_date_ms'];
        $transactionId = $res['receipt']['in_app'][0]['transaction_id'];
        if ($res['status'] != 0) {
            throw new Exception('支付验证错误，错误码'.$res['status']);
        }

        $result = [
            'status' => $status,
            'pay_time' => $payTime ? date("Y-m-d H:i:s",$payTime / 1000) : '',
            'transaction_id' => $transactionId,
        ];
        return $result;
    }


}